package ar.com.ford.it.fullEconomics.persistence.dao;

import java.io.FileNotFoundException;
import java.util.Collection;
import java.util.Vector;
import oracle.toplink.expressions.Expression;
import oracle.toplink.expressions.ExpressionBuilder;
import oracle.toplink.queryframework.ReportQuery;
import oracle.toplink.queryframework.ReportQueryResult;
import oracle.toplink.sessions.Session;
import oracle.toplink.tools.sessionmanagement.SessionManager;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesx01Intfsource;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesx02Fileconten;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesx03Intflog;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesx04Intflevent;
import ar.com.ford.it.webengine.persistence.PersistenceUtil;
import com.ford.it.logging.ILogger;
import com.ford.it.logging.LogFactory;
import com.ford.it.persistence.PersistenceException;
import com.ford.it.persistence.Transaction;

public class LogDao extends Dao {
    private static final String CLASS_NAME = LogDao.class.getName();
    private static final ILogger log = LogFactory.getInstance().getLogger(
            CLASS_NAME);

    /**
     * 
     * @param fullPahtFile
     * @return
     * @throws PersistenceException
     */
    public Teesx01Intfsource getLogSourcebyUpdate(String fullPahtFile)
    throws PersistenceException {
    	//Busco el objeto segun el path que me dan por que no se el pk
        String METHOD_NAME = "insertLogSource";

        log.exiting(CLASS_NAME, METHOD_NAME);
        return (Teesx01Intfsource) super.getObjForUpdate(getIntfSource(fullPahtFile));
    }

    /**
     * Consulta si existe o no el archivo
     * @param fullPahtFile
     * @return
     * @throws PersistenceException
     */
    public boolean repeatFullpathFile(String fullPahtFile) throws PersistenceException{
    	String [] build = {"eesx01IntfNameN"};
    	String [] values = {fullPahtFile};
    	return !this.findAll( (new Teesx01Intfsource()), build , values).isEmpty();
    }
    /**
     * 
     * @param fullPahtFile
     * @return
     * @throws PersistenceException
     */
    public Teesx01Intfsource getIntfSource(String fullPahtFile) throws PersistenceException{
    	String [] build = {"eesx01IntfNameN"};
    	String [] values = {fullPahtFile.toUpperCase()};
    	Collection<Teesx01Intfsource> col = null;
    	col = this.findAll((new Teesx01Intfsource()), build , values);
    	Teesx01Intfsource result = null;
    	if (!col.isEmpty()){
    		result = col.iterator().next();
    	}
		return result;
    }    

    /**
     * Insert TEESX03_INTFLOG Record Definition
     *  Contains the Log of process transactions for a file, including the overall result of the transaction.
     * @param intfLog
     * @throws PersistenceException
     */
        public void insertIntfLog(Teesx03Intflog intfLog)
    throws PersistenceException {
        String METHOD_NAME = "insertIntfLog";
        log.entering(CLASS_NAME, METHOD_NAME);
        Transaction tx = null;
        tx = PersistenceUtil.getTransaction();
        tx.registerInsert(intfLog);
        log.exiting(CLASS_NAME, METHOD_NAME);
    }
    
    /**
     * Insert TEESX04_INTFLEVENT 
     * Contains the detailed events that aroused during the execution of a transaction.
     * @param intfLog
     * @throws PersistenceException
     */
    public void insertIntfleEvent(Teesx04Intflevent intflevent)
    throws PersistenceException {
        String METHOD_NAME = "insertIntfleEvent";
        log.entering(CLASS_NAME, METHOD_NAME);
        Transaction tx = null;
        tx = PersistenceUtil.getTransaction();
        tx.registerInsert(intflevent);
        log.exiting(CLASS_NAME, METHOD_NAME);
    }
    /**
     * Insert TEESX02_FILECONTEN 
     * Contains all the files that are received or that are generated for export, including a field with the whole content of it.
     * @param insertFileConten
     * @throws PersistenceException
     */
    public void insertFileConten(Teesx02Fileconten fileconten)
    throws PersistenceException {
        String METHOD_NAME = "insertFileConten";
        log.entering(CLASS_NAME, METHOD_NAME);
        Transaction tx = null;
        tx = PersistenceUtil.getTransaction();
        tx.registerInsert(fileconten);
        log.exiting(CLASS_NAME, METHOD_NAME);
    }
	public Teesx03Intflog getIntflogyUpdate(Teesx03Intflog intfLog) throws PersistenceException {
        String METHOD_NAME = "insertLogSource";
        Teesx03Intflog intflog= null;
        intflog = (Teesx03Intflog) super.getObjForUpdate(intfLog);
        log.exiting(CLASS_NAME, METHOD_NAME);
        return intflog;
	}
    
    public Teesx03Intflog getLastIntfLog(Teesx01Intfsource source) throws PersistenceException {
        String METHOD_NAME = "getLastIntfLog";
        Teesx03Intflog intfLog = new Teesx03Intflog();
        String[] fields = {"eesx01Intfsource"};
        Object[] values = {source};
        int max = this.getMax(new Teesx03Intflog(), fields, values, "eesx03IlogSequenceK");
        intfLog.setEesx01Intfsource(source);
        intfLog.setEesx03IlogSequenceK(max);
        intfLog = (Teesx03Intflog) this.getObjById(intfLog);
        
        log.exiting(CLASS_NAME, METHOD_NAME);
        return intfLog;
    }

    /**
     * Devuelve el maximo valor del campo "eesx04IevntSequenceK", del Log especificado en el parametro
     * @param obj Instancia de la clase que mapea a la tabla de la cual se desea obtener el maximo
     * @param fields Campos que como condicion deben tener los valores indicados en "values". Si
     * es null entonces se toma el maximo del campo "maxFieldName" sin condiciones
     * @param values Valores de los campos indicados en "fields"
     * @param maxFieldName Campo para el cual se va a buscar el maximo
     * @return Maximo del campo "maxFieldName"
     * @throws PersistenceException
     */
    public Integer getMaxEventSeq(Teesx03Intflog intfLog) throws PersistenceException {
        SessionManager manager = SessionManager.getManager();
        Session session = null;
        ReportQueryResult rqr = null;
        Integer res = null;
        Vector vec = null;
        ExpressionBuilder builder = new ExpressionBuilder();
        Expression exp = null;
        ReportQuery query = null;
        
        try {
            session = manager.getSession(this.getSessionName());
            query = new ReportQuery(builder);
            query.setReferenceClass(new Teesx04Intflevent().getClass());
            query.addMaximum("max", builder.get("eesx04IevntSequenceK"));
            
            if (intfLog != null) {
                exp = builder.get("teesx03Intflog").get("eesx01Intfsource").get("eesx01IntfIdNumberK").equal(intfLog.getEesx01Intfsource().getEesx01IntfIdNumberK());
                exp = exp.and(builder.get("teesx03Intflog").get("eesx03IlogSequenceK").equal(intfLog.getEesx03IlogSequenceK()));
                
                query.setSelectionCriteria(exp);
            }
            
            System.out.println(query.getSQLString());
            
            vec = (Vector) session.executeQuery(query);
            
            // El resultado es unico
            rqr = (ReportQueryResult) vec.get(0);
            res = (Integer) rqr.get("max");
            return res == null ? 0 : res;
        } catch (FileNotFoundException e) {
            
            e.printStackTrace();
            throw new PersistenceException(e);            
        }
    }
    


}
